//
//  MJ_OrderDetailViewController.m
//  UEAssistant
//
//  Created by mac on 2018/1/3.
//  Copyright © 2018年 youyixinxi. All rights reserved.
//

#import "MJ_OrderDetailViewController.h"
#import "MJ_OrderContentCell.h"
#import "MJ_OrderContentLayout.h"
#import "UIImage+Color.h"
#import "UIColor+Extend.h"
#import "PreviewViewController.h"
#import "MJ_PlatDetailLayout.h"
#import "MJ_PlatDetailTableViewCell.h"
@interface MJ_OrderDetailViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic)UITableView *tableView;

@property (strong, nonatomic)UIButton *orderBtn;
@end

@implementation MJ_OrderDetailViewController

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-64-45-18) style:UITableViewStylePlain];
        [_tableView registerClass:[MJ_OrderContentCell class] forCellReuseIdentifier:@"MJ_OrderContentCell"];
        [_tableView registerClass:[MJ_PlatDetailTableViewCell class] forCellReuseIdentifier:@"MJ_PlatDetailTableViewCell"];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

- (UIButton *)orderBtn {
    if (!_orderBtn) {
        _orderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _orderBtn.frame = CGRectMake(50*Radio, Screen_Height-45-9-64, Screen_Width-100*Radio, 45);
        _orderBtn.backgroundColor = [UIColor colorWithHexString:@"0084ff"];
        _orderBtn.layer.cornerRadius = 22.5;
        _orderBtn.layer.masksToBounds = YES;
        [_orderBtn setTitle:@"立即抢单" forState:UIControlStateNormal];
        [_orderBtn addTarget:self action:@selector(orderPressed:) forControlEvents:UIControlEventTouchUpInside];
        _orderBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    }
    return _orderBtn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.shadowImage = [UIImage createImageWithColor:[UIColor colorWithHexString:@"#e0e0e0"]];
    self.title = @"任务信息";
    [self.view addSubview:self.tableView];
    if (_currentType == MJTaskOrderWaitWithPlat) {
        self.orderBtn.layer.cornerRadius = 3.0;
    }
    [self.view addSubview:self.orderBtn];
    if (_currentType == MJTaskOrderTranslateExample || _currentType == MJTaskOrderOngoingWithPlat) {
        [self.orderBtn removeFromSuperview];
        self.tableView.frame = CGRectMake(0, 0, Screen_Width, Screen_Height-64);
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     if (_currentType == MJTaskOrderTranslateExample || _currentType == MJTaskOrderWaitWithPlat || _currentType == MJTaskOrderOngoingWithPlat) {
         return 3;
     }
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_currentType == MJTaskOrderTranslateExample || _currentType == MJTaskOrderWaitWithPlat || _currentType == MJTaskOrderOngoingWithPlat) {
        MJ_PlatDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MJ_PlatDetailTableViewCell" forIndexPath:indexPath];
        cell.layout = [[MJ_PlatDetailLayout alloc] initWithModel:self.resultModel type:_currentType index:indexPath.row];
        cell.index = indexPath.row;
        cell.currentTaskType = _currentType;
        __weak typeof(self) weakSelf = self;
        cell.clickedOpenCellCallback = ^(MJ_PlatDetailTableViewCell *cell) {
            TGLog(@"查看全文");
            __strong typeof(weakSelf) sself = weakSelf;
            [sself lookAtAll];
        };
        cell.clickPhoneIconCallback = ^(MJ_PlatDetailTableViewCell *cell) {
            TGLog(@"拨打电话");
            __strong typeof(weakSelf) sself = weakSelf;
            NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",sself.resultModel.vm_phone];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [sself.view addSubview:callWebview];

        };
        return cell;
    }else{
        MJ_OrderContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MJ_OrderContentCell" forIndexPath:indexPath];
        cell.layout = [[MJ_OrderContentLayout alloc] initWithModel:self.resultModel index:indexPath.row type:_currentType];
        cell.index = indexPath.row;
        //点击查看全文
        __weak typeof(self) weakSelf = self;
        cell.clickedOpenCellCallback = ^(MJ_OrderContentCell *cell) {
            TGLog(@"查看全文");
            __strong typeof(weakSelf) sself = weakSelf;
            [sself lookAtAll];
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_currentType == MJTaskOrderTranslateExample || _currentType == MJTaskOrderWaitWithPlat || _currentType == MJTaskOrderOngoingWithPlat) {
        MJ_PlatDetailLayout *layout = [[MJ_PlatDetailLayout alloc] initWithModel:self.resultModel type:_currentType index:indexPath.row];
        return layout.cellHeight;
    }else{
        MJ_OrderContentLayout *layout = [[MJ_OrderContentLayout alloc] initWithModel:self.resultModel index:indexPath.row type:_currentType];
        return layout.cellHeight;
    };
}

- (void)lookAtAll {
    PreviewViewController *VC = [[PreviewViewController alloc]init];
    //判断来自平台还是来自团队
    VC.sectorId = [NSString stringWithFormat:@"%.0f",self.resultModel.sector_id];
    if (self.currentType == MJTaskOrderWaitWithPlat) {
        VC.plattask_id = self.resultModel.plattask_id;
        VC.segmentIndex = 0;
    }else{
        VC.sectorId = [NSString stringWithFormat:@"%.0f",self.resultModel.sector_id];
    }
    switch (self.currentType) {
        case MJTaskOrderWaitWithPlat:
            VC.connector = platPreviewText_connector;
            
            break;
        case MJTaskOrderWaitWithGroup:
            VC.connector = preview_connector;
//            VC.sectorId = self.resultModel
            break;
        case MJTaskOrderEnterpriseWait:
            VC.connector = @"/enterprise/task/app/getsource";
            break;
        default:
            break;
    }
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)orderPressed:(UIButton *)sender {
    TGLog(@"立即抢单");
    [LSProgressHUD showLoadingToView:self.view];
    [self.view endEditing:YES];
    [self.orderBtn removeFromSuperview];
    //来自平台
    if (self.currentType == MJTaskOrderWaitWithPlat) {
        
        NSDictionary *dic = @{@"plattask_id":self.resultModel.plattask_id,
                              @"vm_Id"       :[NSString stringWithFormat:@"%.0f",self.resultModel.vmId],
                              @"taskName"   :self.resultModel.taskName};
        [AvailableNetWorking postWithUrl:platDropOrder_connector params:dic successHandler:^(id responseObject) {
            
            if ([responseObject[@"code"] intValue] == 200) {
                
                [LSProgressHUD hiddenLoading:self.view];
                //                    _isSuccess = YES;
                shareData.judeHistory_refresh = YES;
                shareData.haveImage = YES;
                [JeemaaNotificationCenter postNotificationName:@"refreshOrderList" object:nil];
                [TopAlertView SetUpbackgroundColor:[UIColor whiteColor] andStayTime:2.0 andImageName:@"抢单成功" andTitleStr:@"恭喜，抢单成功！" andTitleColor:[UIColor blackColor] andCancel:NO];
                shareData.haveImage = NO;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
            else if ([responseObject[@"code"] intValue] == 401){
                
                [LSProgressHUD hiddenLoading:self.view];
                //                    _isSuccess = NO;
                shareData.judeHistory_refresh = YES;
                [JeemaaNotificationCenter postNotificationName:@"refreshOrderList" object:nil];
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"慢了一步，下次早点来哦~" andTitleColor:[UIColor whiteColor] andCancel:NO];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
                
            }
            else{
                [LSProgressHUD hiddenLoading:self.view];
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
                [self.view addSubview:self.orderBtn];
            }
            
        } falureHandler:^(NSError *error) {
            
            [LSProgressHUD hiddenLoading:self.view];
            [self.view addSubview:self.orderBtn];
            
        }];
        
    }

    else{
        NSDictionary *dic = @{@"sectorId"   :[NSString stringWithFormat:@"%.0f",self.resultModel.sector_id],
                              @"ownerId"    :[NSString stringWithFormat:@"%.0f",self.resultModel.owner_id],
                              @"taskId"     :[NSString stringWithFormat:@"%.0f",self.resultModel.task_id],
                              @"vmId"       :[NSString stringWithFormat:@"%.0f",self.resultModel.vmId],
                              @"projectName":(self.resultModel.projectName == nil ? self.resultModel.project_name:self.resultModel.projectName),
                              @"taskName"   :self.resultModel.taskName};
        NSString *url;
        if (self.currentType == MJTaskOrderWaitWithGroup) {
            url = dropOrder_connector;
        }else{
            url = @"/enterprise/task/app/acceptSemi";
        }
        [AvailableNetWorking postWithUrl:url params:dic successHandler:^(id responseObject) {
            
            if ([responseObject[@"code"] intValue] == 200) {
                
                [LSProgressHUD hiddenLoading:self.view];
                shareData.judeHistory_refresh = YES;
                shareData.haveImage = YES;
                [JeemaaNotificationCenter postNotificationName:@"refreshOrderList" object:nil];
                [TopAlertView SetUpbackgroundColor:[UIColor whiteColor] andStayTime:2.0 andImageName:@"抢单成功" andTitleStr:@"抢单成功" andTitleColor:[UIColor blackColor] andCancel:NO];
                shareData.haveImage = NO;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
            else if ([responseObject[@"code"] intValue] == 401){
                
                [LSProgressHUD hiddenLoading:self.view];
                //                    _isSuccess = NO;
                shareData.judeHistory_refresh = YES;
                [JeemaaNotificationCenter postNotificationName:@"refreshOrderList" object:nil];
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"慢了一步，下次早点来哦~" andTitleColor:[UIColor whiteColor] andCancel:NO];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
            else{
                [LSProgressHUD hiddenLoading:self.view];
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
                [self.view addSubview:self.orderBtn];
            }
            
        } falureHandler:^(NSError *error) {
            
            [LSProgressHUD hiddenLoading:self.view];
            [self.view addSubview:self.orderBtn];
            
        }];
    }

}
@end
